/*
 * insam_db.c
 *
 *  Created on: 2011. 7. 3.
 *      Author: wlcraze
 */
#include <stdio.h>
#include <mysql.h>
#include <string.h>
#include <stdlib.h>
#include "def.h"
#include "insam_func.h"

int     runQuery(char *query);
int     fetchRow(void);
void    fetchfieldbyID(int id, char *buffer, int len);
void    fetchfieldbyName(const char *name, char *buffer, int len);
void    errorMsg(char *errMsg);

MYSQL_RES *res;
MYSQL_ROW row;
MYSQL *conn;

int connectDB()
{
	char *db_id = "root";
	char *db_pw = "";
	char *server = "127.0.0.1";
	int port = 3306;
	char *database = "insam"; // DB name

	conn = mysql_init(NULL);
	if (conn == NULL) {
			errorMsg("MySQL init fail");
			return -1;
	}
	if(!mysql_real_connect(conn, server, db_id, db_pw, database, port, NULL, 0)) {
			errorMsg("MySQL connect fail");
			return -2;
	}
	return 0;

}

void closeDB(void)
{
	if (res)	mysql_free_result(res);
	mysql_close(conn);
}

void errorMsg(char *errMsg)
{
	printLog(NULL, "%s : %s",errMsg, mysql_error(conn));
}

int runQuery(char *query)
{
	if(mysql_query(conn, query)) {
		errorMsg("MySQL Query Excute failed");
		return -1;
	}
	res = mysql_store_result(conn);
	return 0;
}

int fetchRow(void)
{
	if(res) {
		row = mysql_fetch_row(res);
		if(!row) {
				errorMsg("MySQL Fetch failed");
				return -1;
		}
		return 0;
	}
	errorMsg("MySQL Query Result Null");
	return -2;
}

void fetchfieldbyID(int id, char *buffer, int len)
{
	if(row[id]) {
		strncpy(buffer, row[id], len);
	} else {
		errorMsg("MySQL Query Result Null");
	}
}

void fetchfieldbyName(const char *name, char *buffer, int len)
{
	MYSQL_FIELD *fields;
	int num_fields;
	int i;

	if(res) {
		num_fields = mysql_num_fields(res);
		fields = mysql_fetch_fields(res);

		for(i = 0; i < num_fields; i++) {
			if(!strcmp(fields[i].name, name) && row[i]) {
				strncpy(buffer, row[i], len);
				return;
			}
		}
	} else {
		errorMsg("MySQL Query Result Null");
	}
}

int verifyUser(char *uid, char *pwd) {
	char query[MAXBUFF_LEN];
	sprintf(query, "select pwd from user_tbl where id = \"%s\"", uid);

	if(runQuery(query) < 0) 		return -1;
	if(fetchRow() < 0)				return -2;		//id 검사
	if(strcmp(pwd, row[0]) != 0) 	return -3;		//password 검사

	sprintf(query, "update user_tbl set recent_time=now() where id = \"%s\"", uid);
	runQuery(query);
	return 1;			//인증 성공
}

short checkPort(char *uid) {
	char query[MAXBUFF_LEN];
	sprintf(query, "select use_port from user_tbl where id = \"%s\"", uid);
	if(runQuery(query) < 0) return -1;
	if(fetchRow() < 0)	return -1;
	short port = (short)(atoi(row[0]));
	if(port!=0)
	 printf("already allocated port : %d\n", port);
	return port;
}

// add. 2011. 07. 03.
short allocatePort(char *uid, char *addr) {
	if (runQuery("select use_port from user_tbl order by use_port") < 0) return -1;

	int i, temp_port, rtn;
	for(i=1; i<MAXPORT; i++) {
		do {
			rtn = fetchRow();
			if(rtn == -2)	return -1;
			if(rtn == -1) 	break;
			temp_port = atoi(row[0]);
		} while(i > temp_port);

		if(i > temp_port) {
			char query[MAXBUFF_LEN];
			sprintf(query, "update user_tbl set use_port=%d, recent_ip=\"%s\" where id=\"%s\"", i, addr, uid);
			printf("<allocatePort>%s\n",query);
			if (runQuery(query) < 0) 	return -1;
			return i;
		}
	}
	return -2;
}

void freePort(char *uid) {
	char query[MAXBUFF_LEN];
	strcpy(query, "update user_tbl set use_port=0");

	if(uid!=NULL) {
		char tmp[50];
		sprintf(tmp, " where id=\"%s\"", uid);
		strcat(query, tmp);
	}
	printf("<freePort>%s\n", query);
	connectDB();
	runQuery(query);
	closeDB();
}

char* getOS(char *uid) {
	char query[MAXBUFF_LEN];
	sprintf(query, "select os from user_tbl where id = \"%s\"", uid);
	if (runQuery(query) < 0 || fetchRow() < 0) return NULL;
	return row[0];
}


